package com.atm.bulksms.data;

import java.util.HashMap;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;

import com.atm.bulksms.data.BulkSMSData.GroupData;
import com.atm.bulksms.data.BulkSMSData.InboxData;
import com.atm.bulksms.data.BulkSMSData.SMSData;
import com.atm.bulksms.data.BulkSMSData.ScheduleData;

public class SMSProvider extends ContentProvider {

	private static final String DATABASE_NAME = "bulksms.db";
	private static final int DATABASE_VERSION = 1;
	    private static final UriMatcher sUriMatcher;

	    private static final int INBOX_MESSAGE = 1;
	    private static final int INBOX_HEADER = 2;
	    private static final int GROUP = 3;
	    private static final int SMS_SCHEDULE = 4;

	    private static HashMap<String, String> messageProjectionMap;
	    private static HashMap<String, String> headerProjectionMap;
	    private static HashMap<String, String> groupProjectionMap;
	    private static HashMap<String, String> scheduleProjectionMap;

	    private static class DatabaseHelper extends SQLiteOpenHelper {

	        DatabaseHelper(Context context) {
	            super(context, DATABASE_NAME, null, DATABASE_VERSION);
	        }

	        @Override
	        public void onCreate(SQLiteDatabase db) {
	            db.execSQL("CREATE TABLE " + BulkSMSData.INBOX_MESSAGE_TABLE_NAME + 
	            		" (" + SMSData._ID + " INTEGER PRIMARY KEY," 
	                    + SMSData.MESSAGE + " TEXT," 
	                    + SMSData.RECEPIENT + " INT,"
	                    + SMSData.STATUS + " BYTE,"
	                    + SMSData.START_TIME + " LONG,"
	                    + SMSData.SENT_TIME + " LONG"
	                   + ");");
	            
	            db.execSQL("CREATE TABLE " + BulkSMSData.INBOX_HEADER_TABLE_NAME + 
	            		" (" + InboxData._ID + " INTEGER PRIMARY KEY," 
	                    + InboxData.NAME + " TEXT," 
	                    + InboxData.DESCRIPTION + " TEXT,"
	                    + InboxData.START_TIME + " LONG"
	                   + ");");
	            
	            db.execSQL("CREATE TABLE " + BulkSMSData.GROUP_TABLE_NAME + 
	            		" (" + GroupData._ID + " INTEGER PRIMARY KEY," 
	                    + GroupData.GROUP_NAME + " TEXT," 
	                    + GroupData.PHONE_NUMBER + " TEXT"
	                   + ");");
	            db.execSQL("CREATE TABLE " + BulkSMSData.SMS_SCHEDULE_TABLE_NAME + 
	            		" (" + ScheduleData._ID + " INTEGER PRIMARY KEY," 
	                    + ScheduleData.MESSAGE + " TEXT," 
	                    + ScheduleData.TIME + " LONG,"
	                    + ScheduleData.NUMBERS + " TEXT"
	                   + ");");
	        }

	        @Override
	        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
	            db.execSQL("DROP TABLE IF EXISTS " + BulkSMSData.INBOX_MESSAGE_TABLE_NAME);
	            db.execSQL("DROP TABLE IF EXISTS " + BulkSMSData.INBOX_HEADER_TABLE_NAME);
	            db.execSQL("DROP TABLE IF EXISTS " + BulkSMSData.GROUP_TABLE_NAME);
	            db.execSQL("DROP TABLE IF EXISTS " + BulkSMSData.SMS_SCHEDULE_TABLE_NAME);
	            onCreate(db);
	        }
	    }

	    private DatabaseHelper dbHelper;

	    @Override
	    public int delete(Uri uri, String where, String[] whereArgs) {
	        SQLiteDatabase db = dbHelper.getWritableDatabase();
	        int count;
	        switch (sUriMatcher.match(uri)) {
	            case INBOX_MESSAGE:
	                count = db.delete(BulkSMSData.INBOX_MESSAGE_TABLE_NAME, where, whereArgs);
	                break;
	            case INBOX_HEADER:
	                count = db.delete(BulkSMSData.INBOX_HEADER_TABLE_NAME, where, whereArgs);
	                break;
	            case GROUP:
	                count = db.delete(BulkSMSData.GROUP_TABLE_NAME, where, whereArgs);
	                break;
	            case SMS_SCHEDULE:
	                count = db.delete(BulkSMSData.SMS_SCHEDULE_TABLE_NAME, where, whereArgs);
	                break;
	            default:
	                throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	    }

	    @Override
	    public String getType(Uri uri) {
	        switch (sUriMatcher.match(uri)) {
	            case INBOX_MESSAGE:
	            case INBOX_HEADER:
	            case GROUP:
	            case SMS_SCHEDULE:
	                return BulkSMSData.CONTENT_TYPE;

	            default:
	                throw new IllegalArgumentException("Unknown URI " + uri);
	        }
	    }

	    @Override
	    public Uri insert(Uri uri, ContentValues initialValues) {
	    	int uriMatch = sUriMatcher.match(uri);
	        if (uriMatch != INBOX_MESSAGE && uriMatch != INBOX_HEADER && uriMatch != GROUP && uriMatch != SMS_SCHEDULE) { throw new IllegalArgumentException("Unknown URI " + uri); }

	        System.out.println(initialValues);
	        ContentValues values;
	        if (initialValues != null) {
	            values = new ContentValues(initialValues);
	        } else {
	            values = new ContentValues();
	        }

	        SQLiteDatabase db = dbHelper.getWritableDatabase();
	        String tableName = null;
	        Uri tableUri = null;
	        switch (uriMatch) {
			case INBOX_MESSAGE:{
				tableName = BulkSMSData.INBOX_MESSAGE_TABLE_NAME;
				tableUri = SMSData.CONTENT_URI;
			}
			break;
			case INBOX_HEADER:{
				tableName = BulkSMSData.INBOX_HEADER_TABLE_NAME;
				tableUri = InboxData.CONTENT_URI;
			}
			break;
			case GROUP:{
				tableName = BulkSMSData.GROUP_TABLE_NAME;
				tableUri = GroupData.CONTENT_URI;
			}
			break;
			case SMS_SCHEDULE:{
				tableName = BulkSMSData.SMS_SCHEDULE_TABLE_NAME;
				tableUri = ScheduleData.CONTENT_URI;
			}
			break;
			default:
				break;
			}
	        System.out.println("table name :"+tableName);
	        System.out.println("table uri :"+tableUri);
	        long rowId = db.insert(tableName, BaseColumns._ID ,values);
	        System.out.println(" rowId :"+rowId);
			if (rowId > 0) {
				Uri noteUri = ContentUris.withAppendedId(tableUri,rowId);
				getContext().getContentResolver().notifyChange(noteUri, null);
				return noteUri;
			}

	        throw new SQLException("Failed to insert row into " + uri);
	    }

	    @Override
	    public boolean onCreate() {
	        dbHelper = new DatabaseHelper(getContext());
	        return true;
	    }

	    @Override
	    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
	        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

	        switch (sUriMatcher.match(uri)) {
	            case INBOX_MESSAGE:
	                qb.setTables(BulkSMSData.INBOX_MESSAGE_TABLE_NAME);
	                qb.setProjectionMap(messageProjectionMap);
	                break;
	            case INBOX_HEADER:
	                qb.setTables(BulkSMSData.INBOX_HEADER_TABLE_NAME);
	                qb.setProjectionMap(headerProjectionMap);
	                break;
	            case GROUP:
	                qb.setTables(BulkSMSData.GROUP_TABLE_NAME);
	                qb.setProjectionMap(groupProjectionMap);
	                break;
	            case SMS_SCHEDULE:
	                qb.setTables(BulkSMSData.SMS_SCHEDULE_TABLE_NAME);
	                qb.setProjectionMap(scheduleProjectionMap);
	                break;
	            default:
	                throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        SQLiteDatabase db = dbHelper.getReadableDatabase();
	        Cursor c = qb.query(db, projection, selection, selectionArgs, null, null, sortOrder);

	        c.setNotificationUri(getContext().getContentResolver(), uri);
	        return c;
	    }
	    
	    public Cursor query(Uri uri, String[] projection, String selection,String groupBy, String[] selectionArgs, String sortOrder) {
	        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

	        switch (sUriMatcher.match(uri)) {
	            case INBOX_MESSAGE:
	                qb.setTables(BulkSMSData.INBOX_MESSAGE_TABLE_NAME);
	                qb.setProjectionMap(messageProjectionMap);
	                break;
	            case INBOX_HEADER:
	                qb.setTables(BulkSMSData.INBOX_HEADER_TABLE_NAME);
	                qb.setProjectionMap(headerProjectionMap);
	                break;
	            case GROUP:
	                qb.setTables(BulkSMSData.GROUP_TABLE_NAME);
	                qb.setProjectionMap(groupProjectionMap);
	                break;
	            case SMS_SCHEDULE:
	                qb.setTables(BulkSMSData.SMS_SCHEDULE_TABLE_NAME);
	                qb.setProjectionMap(scheduleProjectionMap);
	                break;
	            default:
	                throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        SQLiteDatabase db = dbHelper.getReadableDatabase();
	        Cursor c = qb.query(db, projection, selection, selectionArgs, groupBy, null, sortOrder);

	        c.setNotificationUri(getContext().getContentResolver(), uri);
	        return c;
	    }

	    @Override
	    public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
	        SQLiteDatabase db = dbHelper.getWritableDatabase();
	        int count;
	        switch (sUriMatcher.match(uri)) {
	            case INBOX_MESSAGE:
	                count = db.update(BulkSMSData.INBOX_MESSAGE_TABLE_NAME, values, where, whereArgs);
	                break;
	            case INBOX_HEADER:
	                count = db.update(BulkSMSData.INBOX_HEADER_TABLE_NAME, values, where, whereArgs);
	                break;
	            case GROUP:
	                count = db.update(BulkSMSData.GROUP_TABLE_NAME, values, where, whereArgs);
	                break;
	            case SMS_SCHEDULE:
	                count = db.update(BulkSMSData.SMS_SCHEDULE_TABLE_NAME, values, where, whereArgs);
	                break;
	            default:
	                throw new IllegalArgumentException("Unknown URI " + uri);
	        }

	        getContext().getContentResolver().notifyChange(uri, null);
	        return count;
	    }

	    static {
	        sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
	        sUriMatcher.addURI(BulkSMSData.AUTHORITY, BulkSMSData.INBOX_MESSAGE_TABLE_NAME, INBOX_MESSAGE);
	        sUriMatcher.addURI(BulkSMSData.AUTHORITY, BulkSMSData.INBOX_HEADER_TABLE_NAME, INBOX_HEADER);
	        sUriMatcher.addURI(BulkSMSData.AUTHORITY, BulkSMSData.GROUP_TABLE_NAME, GROUP);

	        messageProjectionMap = new HashMap<String, String>();
	        messageProjectionMap.put(SMSData._ID, SMSData._ID);
	        messageProjectionMap.put(SMSData.MESSAGE, SMSData.MESSAGE);
	        messageProjectionMap.put(SMSData.RECEPIENT, SMSData.RECEPIENT);
	        messageProjectionMap.put(SMSData.STATUS, SMSData.STATUS);
	        messageProjectionMap.put(SMSData.SENT_TIME, SMSData.SENT_TIME);
	        messageProjectionMap.put(SMSData.START_TIME, SMSData.START_TIME);
	        
	        headerProjectionMap = new HashMap<String, String>();
	        headerProjectionMap.put(InboxData._ID, InboxData._ID);
	        headerProjectionMap.put(InboxData.NAME, InboxData.NAME);
	        headerProjectionMap.put(InboxData.DESCRIPTION, InboxData.DESCRIPTION);
	        headerProjectionMap.put(InboxData.START_TIME, InboxData.START_TIME);
	        
	        groupProjectionMap = new HashMap<String, String>();
	        groupProjectionMap.put(GroupData._ID, GroupData._ID);
	        groupProjectionMap.put(GroupData.GROUP_NAME, GroupData.GROUP_NAME);
	        groupProjectionMap.put(GroupData.PHONE_NUMBER, GroupData.PHONE_NUMBER);

	        scheduleProjectionMap = new HashMap<String, String>();
	        scheduleProjectionMap.put(ScheduleData._ID, ScheduleData._ID);
	        scheduleProjectionMap.put(ScheduleData.MESSAGE, ScheduleData.MESSAGE);
	        scheduleProjectionMap.put(ScheduleData.TIME, ScheduleData.TIME);
	        scheduleProjectionMap.put(ScheduleData.NUMBERS, ScheduleData.NUMBERS);

	        
	    }
	

}
